var express = require('express');
var app = express();
let WebSocket = require('ws');

const httpPort = 8086;
const wsPort = 8087;


var http = require('http').Server(app);
http.listen(httpPort, function () {
	console.log('Http listening on *: ' + httpPort);
});


var httpServer = require('http').Server({});
httpServer.listen(wsPort);

let clients = new Map()
let games = new Map()

let wsServer = new WebSocket.Server({ server: httpServer, backlog: 1 });
wsServer.on('connection', function (ws, req) {
    console.log(`game ws connected ${req.url}`);
    // parse req into params map
    let params = {}
    for(let param of req.url.split('?')[1].split('&')) {
        let [key, value] = param.split('=')
        params[key] = value
    }

    let gameId, userId
    const currentWs = ws
    if(params.gameId) {
        gameId = params.gameId
        let game = games.get(gameId)
        if(game) {
            game.close()
        }
        games.set(params.gameId, ws)
    } else if(params.userId) {
        userId = params.userId
        let client = clients.get(userId)
        if(client) {
            client.close()
        }
        clients.set(params.userId, ws)
    } else {
        ws.close()
    }
    ws.on('message', function (message) {
        console.log(`game ws message ${message}`);
        try {
            let data = JSON.parse(message)
            if (gameId) {

            } else if (userId) {
                if(data.gameId) {
                    let game = games.get(data.gameId)
                    if(game && game.readyState === WebSocket.OPEN) {
                        game.send(JSON.stringify({
                            userId,
                            type: data.type,
                            data: data.data,
                        }))
                    }
                }
            }
        } catch (e) {
            console.error(e)
        }
    });
    ws.on('close', function () {
        console.log('game ws disconnected');
        if(gameId) {
            if(games.get(gameId) == currentWs) {
                games.delete(gameId)
            }
        } else if(userId) {
            if(clients.get(userId) == currentWs) {
                clients.delete(userId)
            }
        }
    });
});


app.get('/list', function (req, res) {
    res.send([...games.keys()])
});

app.get('/listUser', function (req, res) {
    res.send([...clients.keys()])
});